<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\pay\controller;

use app\pay\model\MemberModel;
use cmf\controller\AdminBaseController;
use think\facade\Db;
use think\db\Query;

class MemberController extends AdminBaseController
{

    /**
     * Notes:用户列表
     * User:
     * DateTime: 2022-01-17 14:57
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        $param = $this->request->param();
        $list = Db::name("user")->alias("u")
            ->field("u.*,ml.name as level_name")
            ->join("member_level ml", "u.level_id = ml.id", "left")
            ->where(function (Query $query) use ($param) {
                $query->where(['u.delete_time' => 0]);
                $query->where(['u.user_type' => 2]);
                if (isset($param['start_time']) && !empty($param['start_time'])) {
                    if (!isset($param['end_time']) || empty($param['end_time'])) {
                        $param['end_time'] = time();
                    }
                    $query->whereTime('u.create_time', 'between', [strtotime($param['start_time']), strtotime($param['end_time'])]);
                }
                if (isset($param['user_login']) && !empty($param['user_login'])) {
                    $query->where('u.user_login', 'like', "%" . $param['user_login'] . "%");
                }
            })
            ->order("u.id desc")
            ->paginate(30)->each(function ($v, $k) {
                //上级用户
                $v['parent_user'] = '无';
                $parent = Db::name("user")->field("user_login")->where(["id" => $v['pid']])->find();
                if ($parent) $v['parent_user'] = $parent['user_login'];
                //总充值,消费
                $where_r = ["user_id" => $v['id'], "status" => 1];
                $where_w = ["user_id" => $v['id'], "status" => 1];
                $v['all_recharge'] = Db::name("member_recharge")->where($where_r)->sum("amount");
                $v['all_withdrawal'] = Db::name("member_withdraw")->where($where_w)->sum("amount");
                return $v;
            });
        $page = $list->render();
        $this->assign("page", $page);
        $this->assign("list", $list);
        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('user_login', isset($param['user_login']) ? $param['user_login'] : '');
        $this->assign('status', isset($param['status']) ? $param['status'] : '');
        return $this->fetch();
    }

    /**
     * 选择上级
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select()
    {
        $ids = $this->request->param('ids');
        $param = $this->request->param();
        $selectedIds = explode(',', $ids);
        $MemberModel = new MemberModel();
        $tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='radio' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
               value='\$id' data-name='\$user_login' \$checked>
    </td>
    <td>\$id</td>
    <td>\$user_login</td>
</tr>
tpl;
        $where = ["delete_time" => 0];
        if (isset($param['keyword']) && !empty($param['keyword'])) {
            $where['user_login'] = ['like', "%" . $param['keyword'] . "%"];
        }
        $categoryTree = $MemberModel->userTableTree($selectedIds, $tpl, $where);
        $categories = Db::name("user")
            ->field("id,pid,user_login")
            ->where($where)
            ->select()->toArray();
        $this->assign('categories', $categories);
        $this->assign('selectedIds', $selectedIds);
        $this->assign('categories_tree', $categoryTree);
        return $this->fetch();
    }

    /**
     * 添加用户页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $member_level = Db::name("member_level")->where(["delete_time" => 0])->select()->toArray();
        $this->assign("member_level", $member_level);
        return $this->fetch();
    }

    /**
     * Notes:执行添加用户
     * User:
     * DateTime: 2022-01-17 16:58
     */
    public function addPost()
    {
        $param = $this->request->param();
        $data['pid'] = $param['pid'];
        $data['user_login'] = $param['user_login'];
        $data['user_nickname'] = $param['user_nickname'];
        $data['level_id'] = $param['level_id'];
        $data['user_type'] = 2;
        $data['user_pass'] = cmf_password($param['user_pass']);
        $data['pay_pass'] = cmf_password($param['pay_pass']);
        $data['invite_code'] = $this->createAgentCode();
        $data['remark'] = $param['remark'];
        $data['create_time'] = time();
        $res = Db::name("user")->save($data);
        if (!$res) $this->error("失败！");
        $this->success("成功！");
    }

    /**
     * Notes:编辑用户页面
     * User:
     * DateTime: 2022-01-17 17:11
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $param = $this->request->param();
        $info = Db::name("user")->where(["id" => $param['id']])->find();
        $member_level = Db::name("member_level")->where(["delete_time" => 0])->select()->toArray();
        $member = Db::name("user")->field("id,user_login")->where(["delete_time" => 0])->select()->toArray();
        $member = array_column($member, "user_login", "id");
        $this->assign("member_level", $member_level);
        $this->assign("member", $member);
        $this->assign("info", $info);
        return $this->fetch();
    }

    /**
     * Notes:执行编辑用户
     * User:
     * DateTime: 2022-01-17 16:58
     */
    public function editPost()
    {
        $param = $this->request->param();
        $data['pid'] = $param['pid'];
        $data['user_login'] = $param['user_login'];
        $data['user_nickname'] = $param['user_nickname'];
        $data['level_id'] = $param['level_id'];
        if (!empty($data['user_pass'])) $data['user_pass'] = cmf_password($param['user_pass']);
        if (!empty($data['pay_pass'])) $data['pay_pass'] = cmf_password($param['pay_pass']);
        $data['remark'] = $param['remark'];
        $data['update_time'] = time();
        $res = Db::name("user")->where(["id" => $param['id']])->save($data);
        if (!$res) $this->error("失败！");
        $this->success("成功！");
    }

    /**
     * Notes:上下分
     * User:
     * DateTime: 2022-01-18 15:14
     * @return mixed
     */
    public function balance()
    {
        $param = $this->request->param();
        $this->assign("id", $param['id']);
        return $this->fetch();
    }

    /**
     * Notes:执行上下分
     * User:
     * DateTime: 2022-01-18 15:31
     */
    public function doBalance()
    {
        $res = 0;
        $param = $this->request->param();
        $user = Db::name("user")->field("id,user_login,balance")->where(["id" => $param['id']])->find();
        $balance = $user['balance'];
        if ($param['type'] == 1) {
            $table = "member_recharge";
            $data['balance'] = $balance + $param['balance'];
            $dat['type'] = 4;
            $log_amount = $param['balance'];
        } else {
            $table = "member_withdraw";
            $data['balance'] = $balance - $param['balance'];
            $dat['type'] = 2;
            $log_amount = 0 - $param['balance'];
        }
        if ($data['balance'] >= 0) {
            try {
                $data['update_time'] = time();
                Db::startTrans();
                $mem = Db::name("user")->where(["id" => $param['id']])->save($data);
                //添加充值提现记录
                $dat['user_id'] = $param['id'];
                $dat['amount'] = $param['balance'];
                $dat['status'] = 1;
                $dat['remark'] = '后台操作';
                $dat['create_time'] = date("Y-m-d H:i:s");
                $rec = Db::name($table)->insert($dat);
                //添加资金日志
                $log['user_id'] = $param['id'];
                $log['user'] = $user['user_login'];
                $log['type'] = $param['type'];
                $log['before_amount'] = $balance;
                $log['money'] = $log_amount;
                $log['after_amount'] = $data['balance'];
                $log['notice'] = '后台操作';
                $log['create_time'] = date("Y-m-d H:i:s");
                $res_log = Db::name("moneylog")->insert($log);
                Db::commit();
                if ($mem && $rec && $res_log) {
                    $res = 1;
                } else {
                    Db::rollback();
                }
            } catch (\Exception $e) {
                Db::rollback();
            }
        } else {
            $this->error("余额不足");
        }
        if (!$res) $this->error("失败！");
        $this->success("成功！");
    }

    /**
     * Notes:上下积分
     * User:
     * DateTime: 2022-01-18 15:14
     * @return mixed
     */
    public function score()
    {
        $param = $this->request->param();
        $this->assign("id", $param['id']);
        return $this->fetch();
    }

    /**
     * Notes:执行上下积分
     * User:
     * DateTime: 2022-01-18 15:31
     */
    public function doScore()
    {
        $param = $this->request->param();
        $user = Db::name("user")->field("id,user_login,score,score_total")->where(["id" => $param['id']])->find();
        if ($param['type'] == 1) {
            $data['score'] = $user['score'] + $param['number'];
            $data['score_total'] = $user['score_total'] + $param['number'];
        } else {
            $data['score'] = $user['score'] - $param['number'];
        }
        if ($data['score'] >= 0) {
            try {
                $res = 0;
                Db::startTrans();
                $data['update_time'] = time();
                $mem = Db::name("user")->where(["id" => $param['id']])->save($data);
                //添加积分记录
                $dat['user_id'] = $param['id'];
                $dat['type'] = 4;
                $dat['before_amount'] = $user['score'];
                $dat['number'] = $param['number'];
                $dat['after_amount'] = $data['score'];
                $dat['remark'] = '后台操作';
                $dat['create_time'] = date("Y-m-d H:i:s");
                $rec = Db::name("jf_changes")->insert($dat);
                Db::commit();
                if ($mem && $rec) {
                    $res = 1;
                } else {
                    Db::rollback();
                }
            } catch (\Exception $e) {
                Db::rollback();
            }
        } else {
            $this->error("积分不足");
        }
        if (!$res) $this->error("失败！");
        $this->success("成功！");
    }

    /**
     * Notes:启用/停用
     * User:
     * DateTime: 2022-01-17 15:10
     * @throws \think\db\exception\DbException
     */
    public function publish()
    {
        $param = $this->request->param();
        if (isset($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            Db::name("user")->where('id', $id)->update(['status' => $param['status'], 'update_time' => time()]);
            $this->success("成功！", '');
        }

        if (isset($param['ids']) && isset($param["yes"])) {
            $ids = $this->request->param('ids/a');
            Db::name("user")->where('id', 'in', $ids)->update(['status' => 1, 'update_time' => time()]);
            $this->success("成功！", '');
        }
    }

    /**
     * 签到列表
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function signLog()
    {
        $param = $this->request->param();
        $list = Db::name("sign_log")->alias("s")
            ->field("u.user_login,s.*")
            ->join("user u", "u.id = s.user_id", "left")
            ->where(function (Query $query) use ($param) {
                if (isset($param['start_time']) && !empty($param['start_time'])) {
                    if (!isset($param['end_time']) || empty($param['end_time'])) {
                        $param['end_time'] = time();
                    }
                    $query->whereTime('s.create_time', 'between', [strtotime($param['start_time']), strtotime($param['end_time'])]);
                }
                if (isset($param['user_login']) && !empty($param['user_login'])) {
                    $query->where('u.user_login', 'like', "%" . $param['user_login'] . "%");
                }
            })
            ->order("s.id desc")
            ->paginate(30);
        $page = $list->render();
        $this->assign("page", $page);
        $this->assign("list", $list);
        $this->assign('start_time', isset($param['start_time']) ? $param['start_time'] : '');
        $this->assign('end_time', isset($param['end_time']) ? $param['end_time'] : '');
        $this->assign('user_login', isset($param['user_login']) ? $param['user_login'] : '');
        return $this->fetch();
    }

    /**
     * Notes:删除
     * User:
     * DateTime: 2022-01-17 15:10
     * @throws \think\Exception
     */
    public function delete()
    {
        $this->deleteInfo("user");
        $this->success("删除成功");
    }

    function createAgentCode()
    {
        $str = array_merge(range(1, 9), range('A', 'Z'));
        shuffle($str);
        $str = implode('', array_slice($str, 0, 8));
        $id = Db::name("user_agent")->where(["agent_code" => $str])->value("id");
        if ($id) {
            $this->createAgentCode();
        } else {
            return $str;
        }
    }

}
